//
//  LDUserInfo.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/4/21.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SVProgressHUD
import YYCache

class LDUserInfo:NSObject{
    
    
    internal var expectedjobscount:Int?
    internal var userInfoModel:LDUserInfoModel?
    
    internal var myResumeModel:LDMyResumeModel?
    
    internal var userInfoDict = [String:AnyObject]()
    internal var myRemuseInfoDict = [String:AnyObject]()
    internal var userCacheManger:YYCache?
    
    lazy var userPhoneNo:String = {
        
        return DDLoginUserManager.account() as String
    }()
    
    lazy var userToken:String = {
        
        let str = DDLoginUserManager.token() as String
        return str
    }()
    
    lazy var userPhoneAndTokenDic:Dictionary<String,String>? = {
        
        let dict = ["hashedpassword":DDLoginUserManager.token() as String,"mobile":DDLoginUserManager.account() as String]
        return dict
        
    }()
    
   
    
    //更新微简历信息
    func updataJobFinderMyResume(success:((dict:Dictionary<String, AnyObject>)->Void)?,failure:((error:
        AnyObject)->Void)?) {
        
        LDNetWorkManager().LoginPOST(LDJobfinderAPI.view.myself.resume, parameters: nil, success: { [weak self] (value) in
            
            LDUserInfo.sharedInstance.saveToCache("myReesumeInfo", value: value as! Dictionary<String,AnyObject>,success: {
                
            })
            
            self?.myRemuseInfoDict.removeAll()
            self?.myRemuseInfoDict = value as? [String : AnyObject] ?? [String : AnyObject]()
            
            self?.myResumeModel = LDMyResumeModel.yy_modelWithDictionary((self?.myRemuseInfoDict)!)
            
            if success != nil {
                success!(dict: (self?.myRemuseInfoDict)!)
            }
            
        }) { (data, error) in
            
            if failure != nil {
                failure!(error: data)
            }
//            SVProgressHUD.showErrorWithStatus(data as! String)
            LDShowHUB.shareInstance.showBarStatus(data as! String)
        }
    }
    //请求微简历信息
    func queryJobFinderMyResume(success:(dict:Dictionary<String, AnyObject>)->Void,failure:((error:
        AnyObject)->Void)?) {
        
        LDNetWorkManager().LoginPOST(LDJobfinderAPI.view.myself.resume, parameters: nil, success: { [weak self] (value) in
            
            self?.myRemuseInfoDict.removeAll()
            self?.myRemuseInfoDict = value as! [String : AnyObject]
            self?.myResumeModel = LDMyResumeModel.yy_modelWithDictionary((self?.myRemuseInfoDict)!)
            
            // 打印json
//            let str = self?.myRemuseInfoDict.jsonString() ?? String()
//            print(str)
            
            LDUserInfo.sharedInstance.saveToCache("myReesumeInfo", value: (self?.myRemuseInfoDict)!, success: nil)
            
            NSOperationQueue.mainQueue().addOperationWithBlock({ 
                success(dict: (self?.myRemuseInfoDict)!)
            })
            
            
        }) { (data, error) in
            
            
            LDUserInfo.sharedInstance.readFromCache("myReesumeInfo", success: { [weak self] (key, value) in
                
                self?.myRemuseInfoDict = value as! [String : AnyObject]
                if failure != nil {
                    
                    NSOperationQueue.mainQueue().addOperationWithBlock({
                        failure!(error: (self?.myRemuseInfoDict)!)
                    })
                } }, failure: nil)
            
//            SVProgressHUD.showErrorWithStatus(data as! String)
            LDShowHUB.shareInstance.showBarStatus(data as! String)
        }
    }
    
    //更新个人信息
    func updateUserInfo(success:((dict:Dictionary<String, AnyObject>)->Void)?,failure:((error:
        AnyObject)->Void)?) {
        
        LDNetWorkManager().LoginPOST(LDJobfinderAPI.query.profile, parameters:nil, success: {[weak self] (value) in
            
            self?.userInfoDict.removeAll()
            self?.userInfoDict = value as! [String : AnyObject]
            self?.userInfoModel = LDUserInfoModel.yy_modelWithDictionary(value as! [NSObject : AnyObject])
            
            self?.saveToCache("userInfoDict",value: (self?.userInfoDict)!, success: {

                if success != nil {
                    
                    dispatch_async(dispatch_get_main_queue(), {
                        success!(dict: (self?.userInfoDict)!)
                    })
                    
                }
//                debugPrint("缓存成功")
            })
            
            }, failure: { value,error in
                
                if failure != nil {
                    failure!(error: value)
                }
        })
    }
    
    //query个人信息
    func queryUserInfo(success:((dict:Dictionary<String, AnyObject>)->Void),failure:((error:
        AnyObject)->Void)?) {
        
        LDNetWorkManager().LoginPOST(LDJobfinderAPI.query.profile, parameters:nil, success: {[weak self] (value) in
            
            self?.userInfoDict.removeAll()
            self?.userInfoDict = value as! [String : AnyObject]
            self?.userInfoModel = LDUserInfoModel.yy_modelWithDictionary(value as! [NSObject : AnyObject])
            
            self?.saveToCache("userInfoDict",value: (self?.userInfoDict)!, success: nil)
            success(dict: (self?.userInfoDict)!)
            
            }, failure: { data,error in
                
                LDCacheManager.shareInstance.readFromCache("userInfoDict", colsure: { (key, value) in
                    
                    if value != nil {
                        
                        success(dict: (value as? Dictionary<String, AnyObject>)!)
                    } else {
                        
                        if failure != nil {
                            
                            failure!(error: data)
                        }
                    }
                })
                
                
        })
    }
    
    override init(){
        
        super.init()
        userInfoModel = LDUserInfoModel()
        myResumeModel = LDMyResumeModel()
        
        userCacheManger = YYCache.init(path: LDCache.JobFinderInfoString)
        
//        updataJobFinderMyResume({ (dict) in
//            let xx = dict.jsonString()
//            }, failure: nil)
        
        LDNetWorkManager().LoginPOST(LDJobfinderAPI.query.profile, parameters:nil, success: {[weak self] (value) in
            
            self?.userInfoDict = value as! Dictionary<String, AnyObject>
            self?.saveToCache("userInfoDict",value: (self?.userInfoDict)!, success: {
                debugPrint("缓存成功")
            })
            
            }, failure: {[weak self] _,error in
                
                self?.readFromCache("userInfoDict", success: { (key, value) in
                    
                    guard value != nil else {
                        return
                    }
                    
                    self?.userInfoDict = value as! Dictionary<String, AnyObject>
                    
//                    self?.userInfo = LDUserInfoModel.yy_modelWithDictionary((self?.userInfoDict)! as [NSObject : AnyObject])
                    
                    }, failure: nil)
            })
    }
    
    //缓存
    func saveToCache(key:String,value:NSCoding,success:(()->())?) {
        
        userCacheManger?.removeObjectForKey(key, withBlock: { [weak self] (name) in
//            debugPrint("删除\(name)成功")
            self?.userCacheManger?.setObject(value, forKey: key, withBlock: {
//                debugPrint("缓存\(name)成功")
                if success != nil {
                    success!()
                }
            })
            })
    }
    //读取
    func readFromCache(key:String, success:(key:String,value:NSCoding?)->(),failure:(()->())?) {
        let value = userCacheManger?.objectForKey(key)
        
        if value != nil {
            
            success(key: key,value: value)
        } else {
            
            if failure != nil {
                failure!()
            }
        }
    }
    //入口
    class var sharedInstance:LDUserInfo {
        struct Staics {
            static let instance = LDUserInfo()
        }
        return Staics.instance
    }
}